var DatePicker_Instances = [];

function DatePicker(id)
{
    // Public Properties
    this.id = id;
    this.dateFormat = "dmy";
	this.cssClass = "";
	this.enabled = true;
	this.type = "FullDate"; // FullDate o MonthYear 
	
    // Private Properties
    this.isexpanded = false;
    this.isWritten = false;
    this.calendar;
        
    // Public Functions
    this.dispose = DatePicker_Dispose;
    this.clone = DatePicker_Clone;
    this.show = DatePicker_Show;    
    this.showIn = DatePicker_ShowIn;
    
    this.getValue = DatePicker_GetValue;
    this.setValue = DatePicker_SetValue;
    this.setDateValue = DatePicker_SetDateValue;
    this.clearValue = DatePicker_ClearValue;
    
    this.expand = DatePicker_Expand;
    this.colapse = DatePicker_Colapse;

    this.enable = DatePicker_Enable;
    this.disable = DatePicker_Disable;

    // Private Functions
    this.getCalendar = DatePicker_GetCalendar;
    this.dateParse = DatePicker_DateParse;
    this.parseFullDate = DatePicker_ParseFullDate;
    this.parseMonthYear = DatePicker_ParseMonthYear;
    this.refreshInputValue = DatePicker_RefreshInputValue;        
    this.getInputValue = DatePicker_GetInputValue;   
    
    // Events
    this.onChange = "";
    
    DatePicker_Instances[id] = this;
}


// -----------------------------------------------------------------------------------------------------------------
//                                              Public Functions
// -----------------------------------------------------------------------------------------------------------------

function DatePicker_Dispose()
{
	var divcont = document.getElementById("divcont" + this.id);
	
	if(divcont) {
	    if(divcont.parentElement)
	        divcont.parentElement.removeChild(divcont);
	    else
	        divcont.parentNode.removeChild(divcont);
	}

	if(FocusManager.isFocused(this))
		FocusManager.controlonfocus = "";
    
	delete DatePicker_Instances[this.id];
}

function DatePicker_Clone(newId)
{
    var newDatePicker = new DatePicker(newId);

	newDatePicker.dateFormat = this.dateFormat;
	newDatePicker.cssClass = this.cssClass;
	newDatePicker.enabled = this.enabled;
	
    newDatePicker.calendar = this.getCalendar().clone("calendar_" + newId);
    newDatePicker.calendar.parentID = newId;
    
    return newDatePicker;
}

function DatePicker_Show(containerID)
{
    var container = document.getElementById(containerID);
    if(container)
        this.showIn(container);
}

function DatePicker_ShowIn(container)
{
    var focusFunction = "";
    var checkFunction = "";
    var disabledString = "";
    var strValue = "";
    var buttonClass;
    var func = "";
    var inputClass;
    
    if (this.enabled) {
        focusFunction = "DatePicker_SetFocus(\'" + this.id + "\');";    
        checkFunction = "onfocusout=\"DatePicker_CheckValue(\'" + this.id + "\')\" onkeyup=\"DatePicker_OnKeyUp(\'" + this.id + "\', event)\"";    
        func = "onclick=\"DatePicker_ColapseExpand('" + this.id + "')\" onmouseover=\"Common.on(this)\" onmouseout=\"Common.off(this)\"";
        buttonClass = "openButton";
        inputClass = "input";
    }
    else {
        disabledString = "disabled = \"disabled\"";
        buttonClass = "openButtonDisabled";
        inputClass = "inputDisabled";
    }

    if(this.calendar.validDate) {
        var date = this.calendar.getDate(date);
        strValue = this.getInputValue(date.year, date.month, date.day);
    }
            
    // Dibujado del control
    var html = "";

    html += "<span id=\"divcont" + this.id + "\" name=\"divcont" + this.id + "\" style=\"position:relative; top:0px; left:0px; z-index:2\">";
    html += "   <table onclick=\"" + focusFunction + "\" cellpadding=0 cellspacing=0  z-index:0; table-layout:fixed\">";
    html += "       <tr>";
    html += "          <td datePicker=\"yes\" nowrap style=\"vertical-align:middle;\">";
    html += "              <input datePicker=\"yes\" id=\"" + this.id + "\" " + checkFunction + " onfocusin=\"" + focusFunction + "\" onfocus=\"" + focusFunction + "\" " + disabledString + " class=\"" + inputClass + "\" type=\"text\" value=\"" + strValue + "\">";
    html += "          </td>";
    html += "          <td></td>";
    html += "          <td datePicker=\"yes\" nowrap align=\"right\" style=\"vertical-align:middle;\">";
    html += "              <div id=\"button_" + this.id + "\" class=\"" + buttonClass + "\" classRollOver=\"openButtonOn\" " + func + ">&nbsp;...&nbsp;</div>";
    html += "          </td>";
    html += "       </tr>";
    html += "   </table>";
    html += "   <div datePicker=\"yes\" id=\"calendarcont_" + this.id + "\" style=\"position:absolute; left:0; visibility:hidden\"; z-index:1\">";
    html +=         this.calendar.show();
    html += "   </div>";
    html += "</span>";
    
    container.innerHTML = html;
    
    this.isWritten = true;
}

function DatePicker_GetValue()
{
    var objValue = document.getElementById(this.id);
    return objValue.value;
}

function DatePicker_RefreshInputValue(year, month, day)
{
    var input = document.getElementById(this.id);
    input.value = this.getInputValue(year, month, day);
    
    this.colapse();
    
    if(this.onChange)
        eval(this.onChange + "('" + this.id + "','" + input.value + "')");
}

function DatePicker_SetValue(strValue)
{
    var date = this.dateParse(strValue);
    
    if(date != null) {
        var calendar = this.getCalendar();
        calendar.setDate(date);
        
        if(this.isWritten)
            this.refreshInputValue(date.year, date.month, date.day);
    }
}

function DatePicker_SetDateValue(dateTime)
{
    var date = {year: dateTime.getYear(), month: dateTime.getMonth()+1, day: dateTime.getDate()};

    var calendar = this.getCalendar();
    calendar.setDate(date);
    
    if(this.isWritten)
        this.refreshInputValue(date.year, date.month, date.day);
}

function DatePicker_ClearValue()
{
    var calendar = this.getCalendar();
    calendar.emptyDate();
    
    if(this.isWritten) {
        var input = document.getElementById(this.id);
        input.value = "";
    }
}

function DatePicker_Expand(id)
{
	var div  = document.getElementById("calendarcont_" + this.id);
	div.style.visibility = "visible";
	
	this.isexpanded = true;
}

function DatePicker_Colapse(id)
{
	var div  = document.getElementById("calendarcont_" + this.id);
	div.style.visibility = "hidden";
	
	this.isexpanded = false;
}

function DatePicker_Enable()
{
    var button = document.getElementById("button_" + this.id);
    button.className = "button";
    button.classRollOver = "buttonOn";    
    Common.setEventHandler(button, "onclick", "DatePicker_ColapseExpand('" + this.id + "')");
    Common.setEventHandler(button, "onmouseover", "Common.on(this)");
    Common.setEventHandler(button, "onmouseout", "Common.off(this)");    

    var input = document.getElementById(this.id);
    input.disabled = false;
    input.className = "input";
}

function DatePicker_Disable()
{
    var button = document.getElementById("button_" + this.id);
    button.className = "buttonDisabled";
    Common.setEventHandler(button, "onclick", "");
    Common.setEventHandler(button, "onmouseover", "");    
    Common.setEventHandler(button, "onmouseout", "");
        
    var input = document.getElementById(this.id);
    input.setAttribute("disabled", "disabled");
    input.disabled = true;
    input.className = "inputDisabled";
}


// -----------------------------------------------------------------------------------------------------------------
//                                              Funciones Privadas
// -----------------------------------------------------------------------------------------------------------------

function DatePicker_GetCalendar()
{
    if(this.type == "FullDate")
        return Calendar_Get("calendar_" + this.id);
    else
        return MonthCalendar_Get("calendar_" + this.id);
}

function DatePicker_DateParse(strDate)
{
    if(this.type == "FullDate")
        return this.parseFullDate(strDate);
    else
        return this.parseMonthYear(strDate);
}

function DatePicker_ParseFullDate(strDate)
{
    if(!Common.isValidDate(strDate, this.dateFormat))
        return null;
    
    var separator;
    
    if(strDate.indexOf("/") < 0)
        separator = "-";
    else
        separator = "/";
    
    var pos1 = strDate.indexOf(separator, 0);
    var pos2 = strDate.indexOf(separator, pos1+1);
    var firstComp = strDate.substring(0, pos1);
    var secondComp = strDate.substring(pos1+1, pos2);
    var year = strDate.substring(pos2+1, strDate.length);
       
    if(year.length<4)   
        year = Common.getFullYear(parseInt(year, 10));
    else
        year = parseInt(year, 10);
        
    if(this.dateFormat == "dmy")
        return {year:year, month:parseInt(secondComp, 10), day:parseInt(firstComp, 10)};
    else
        return {year:year, month:parseInt(firstComp, 10), day:parseInt(secondComp, 10)};
}

function DatePicker_ParseMonthYear(strDate)
{
    var separator;
    
    if(strDate.indexOf("/") < 0)
        separator = "-";
    else
        separator = "/";
    
    var pos = strDate.indexOf(separator, 0);
    var strMonth = strDate.substring(0, pos);
    var strYear = strDate.substring(pos+1, strDate.length);
    var year;
       
    if(strYear.length < 4)   
        year = Common.getFullYear(parseInt(strYear, 10));
    else
        year = parseInt(strYear, 10);

    var month = parseInt(strMonth, 10);

    if( (month >= 1) && (month <= 12) && (!isNaN(month)) && (!isNaN(year)) )
        return {year:year, month:month, day:1};
    else
        return null;
}

function DatePicker_GetInputValue(year, month, day)
{
    var strDay = day.toString();
    if(day<10)
        strDay = "0" + strDay;
    
    var strMonth = month.toString();
    if(month<10)
        strMonth = "0" + strMonth;

    var inputValue;
    
    if(this.type == "MonthYear")
        inputValue = strMonth + "/" + year;    
    else if(this.dateFormat=="dmy")
        inputValue = strDay + "/" + strMonth + "/" + year;
    else
        inputValue = strMonth + "/" + strDay + "/" + year;
    
    return inputValue;
}

// -----------------------------------------------------------------------------------------------------------------
//                                              Funciones de foco
// -----------------------------------------------------------------------------------------------------------------

FocusManager.registerControl("DatePicker_DisposeFocus");

function DatePicker_DisposeFocus(id)
{
    var datePicker = DatePicker_Get(id);
    
    if(datePicker) {
        datePicker.colapse();
        
		var input = document.getElementById(id);
        input.className = "input";        
    }
}

function DatePicker_SetFocus(id)
{
    var datePicker = DatePicker_Get(id);
    
    if(datePicker) {
	    FocusManager.setFocus(id);
	    
	    if(datePicker.enabled) {
		    var input = document.getElementById(id);
            input.className = "inputOnFocus";
        }
	}
}

// -----------------------------------------------------------------------------------------------------------------
//                                              Funciones Externas
// -----------------------------------------------------------------------------------------------------------------

function DatePicker_ColapseExpand(id)
{
	var datePicker = DatePicker_Instances[id];
	
	if(datePicker.isexpanded)
        datePicker.colapse(id);
	else
        datePicker.expand(id);
}

function DatePicker_RefreshValue(id, year, month, day)
{
    DatePicker_DisposeFocus(id);

    var datepicker = DatePicker_Get(id);
    datepicker.refreshInputValue(year, month, day);
}

function DatePicker_CheckValue(id)
{
	var datePicker = DatePicker_Instances[id];
    var input = document.getElementById(id);
    var date = datePicker.dateParse(input.value);
    
    if(date != null) {
	    datePicker.getCalendar().setDate(date);
	    datePicker.refreshInputValue(date.year, date.month, date.day);
	}
	else {
	    datePicker.getCalendar().emptyDate();
	    input.value = "";
	}
}

function DatePicker_OnKeyUp(id, ev)
{
    var ev = ev || window.event;
    
    if(ev.keyCode==13) { // Enter
        DatePicker_CheckValue(id);
    }
}

function DatePicker_OnKeyDown(id, ev)
{
    var ev = ev || window.event;
    
    if(ev.keyCode==9) { // Tab
        DatePicker_DisposeFocus(id);  
    }  
}

function DatePicker_Get(id)
{
    return DatePicker_Instances[id];
}